package control;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedHashMap;

import dao.AbilityDaoImpl;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import utils.DBconn;

@WebServlet(name = "MenuServlet")
public class MenuServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        /**
         * 接收信息
         */
        String key = request.getParameter("key");
        String value = request.getParameter("value");

        //检检查传入的值是否为空，第一次进入菜单页面时，没有点击，所以值为空
        if (key == null || value == null)
            return;

        // System.out.println(key);
        // System.out.println(value);

        AbilityDaoImpl abilityDao = new AbilityDaoImpl();
        //不空时，插入数据库
        try {
            abilityDao.setAbility(key, value);
            // System.out.println("更新成功");
        } catch (SQLException e) {
            e.printStackTrace();
        }


        String apikey = "apikey";
        String tulingKey = "fdd81beab5994d278b86b6006bc0a1ee";
        //创建json数据,并将上文中的接受数据填入
        JSONObject sendJsJsonObject = new JSONObject();
        try {
            sendJsJsonObject.put(key, value);
            System.out.println(sendJsJsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /**
         * 将（数据库信息）发送信息到显示js,使页面数据为上次的数据
         */
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        try {
            JSONArray sendJsArray = tranJson();
            PrintWriter out = response.getWriter();
            out.write(sendJsArray.toString());
            out.flush();
        } catch (SQLException | JSONException e) {
            e.printStackTrace();
        }

        /**
         * 对需要发送至图灵服务器的信息进行信息添加（如apikey等）
         *
         * 图灵技能开关json实例
         * data: {                                  ------->sendTulingObject
         *         "apikey": " apikey ",            ------->sendTulingObject.put(apikey,tulingKey);
         *         "data": {                        ------->sendTulingObject.put(data,dataObject);
         *             "list": [                    ------->dataObject.put(list,sendListArray)
         *                  { "news": false }       ------->sendListArrayObject
         *                      ]
         *                 }
         *     }
         */
        //发送至图灵的完整信息： sendTulingObject对象
        JSONObject sendTulingObject = new JSONObject();
        try {
            //整体信息添加key
            sendTulingObject.put(apikey, tulingKey);
            //由内向外封装信息
            //先封装添加 list内容 -->{ "news": false }
            JSONObject sendListArrayObject = new JSONObject();
            sendListArrayObject.put(key, value);
            System.out.println("sendListArrayObject:" + sendListArrayObject);
            //在将list整体封装为jsonArray格式
            JSONArray sendListArray = new JSONArray();
            sendListArray.put(sendListArrayObject);
            System.out.println("sendListArray:" + sendListArray);
            //将list的内容与键值list对应起来,并添加进dataObject中
            JSONObject dataObject = new JSONObject();
            String list = "list";
            dataObject.put(list, sendListArray);
            System.out.println("dataObject" + dataObject);
            //将data装入整体信息中
            String data = "data";
            sendTulingObject.put(data, dataObject);
            System.out.println("sendTulingObject:" + sendTulingObject);

        } catch (JSONException e) {
            e.printStackTrace();
        }


        //发送到图灵服务器
        send(sendTulingObject);


    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doPost(request, response);
    }

    /**
     * 将对应的数据库转为jsonArray数据
     *
     * @return
     * @throws SQLException
     * @throws JSONException
     */
    private JSONArray tranJson() throws SQLException, JSONException {
        // DateDaoImpl dateDao = new DateDaoImpl();
        DBconn.init();
        String sql = "select * from voicerobot.ability;";
        // ResultSet  rs = dateDao.getTableAll(sql);
        ResultSet rs = DBconn.selectSql(sql);
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();

        JSONArray array = new JSONArray();
        while (rs.next()) {
            JSONObject jsonObject = new JSONObject(new LinkedHashMap());
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnLabel(i);
                String value = rs.getString(columnName);
                jsonObject.append(columnName, value);
            }
            array.put(jsonObject);
        }
        // System.out.println("转换json数据");
        // System.out.println(array.toString()+"\n");
        DBconn.closeConn();
        return array;
    }

    /**
     * 将从js接受后的消息发送到图灵服务器，并接受回馈
     *
     * @param jsonObject
     * @return
     */
    private String send(JSONObject jsonObject) throws IOException {
        StringBuffer stringBuffer = new StringBuffer();
        String tulingUrl = "http://www.tuling123.com/v1/robot/ability";

        //创建url资源
        URL url = new URL(tulingUrl);
        // 建立http连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置允许输出
        conn.setDoOutput(true);
        // 设置允许输入
        conn.setDoInput(true);
        // 设置不用缓存
        conn.setUseCaches(false);
        // 设置传递方式
        conn.setRequestMethod("POST");
        // 设置文件字符集:
        conn.setRequestProperty("Charset", "UTF-8");
        // 设置文件类型:
        conn.setRequestProperty("Content-Type", "application/json;");
        //设置发送数据
        byte[] data = (jsonObject.toString()).getBytes();
        // 开始连接请求
        conn.connect();
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        // 写入请求的字符串
        out.write((jsonObject.toString()).getBytes());
        out.flush();
        out.close();

        System.out.println(conn.getResponseCode());

        if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
            System.out.println("连接成功");
            //请求返回的数据
            InputStream input = conn.getInputStream();

            String readLine = new String();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
            while ((readLine = reader.readLine()) != null) {
                stringBuffer.append(readLine).append("\n");
            }
            reader.close();
            System.out.println(stringBuffer.toString());
        } else {
            System.out.println("error++");
        }
        return stringBuffer.toString();
    }
}
